package com.wawayaya.bookreader.worddict;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.wawayaya.util.BooleanHolder;
import com.wawayaya.util.FileUtil;
import com.wawayaya.util.TLog;

public class Simpledownloadonesmallfile {

	@SuppressWarnings("finally")
	public static boolean downloadonefile(String surl, String ssavedpath, BooleanHolder bcontinue, int iconnectiontimeout, int ireadtiemout) {
		URL url = null;
		HttpURLConnection httpURLConnection = null;
		InputStream is = null;
		RandomAccessFile raf = null;
		boolean bdone = false;
		try{
			 url = new URL(surl);
			 httpURLConnection = (HttpURLConnection) url.openConnection();
	         httpURLConnection.setConnectTimeout(iconnectiontimeout); 
	         httpURLConnection.setReadTimeout(ireadtiemout);
	         httpURLConnection.setRequestMethod("GET"); 
	         if(!bcontinue.get()) {
	        	 return false;
	         }	 
	         is = httpURLConnection.getInputStream(); 	
		     File f = new File(ssavedpath);
		     raf = new RandomAccessFile(f, "rw");
		     byte[] buf = new byte[4096]; 
		     int iread = 0; 		     
		     while((iread = is.read(buf)) != -1 && bcontinue.get()) {
		    	 raf.write(buf, 0, iread);		    	 
		     }
			 bdone = bcontinue.get();
		}catch (MalformedURLException e) {
			TLog.log("Sound ThreadDownloadSamllFile : downloadonefile : MalformedURLException : " + e);
        }  
		catch(FileNotFoundException e){
			TLog.log("Sound ThreadDownloadSamllFile : downloadonefile : FileNotFoundException : " + e);
		}		
        catch (IOException e) {
			TLog.log("Sound ThreadDownloadSamllFile : downloadonefile : IOException : " + e);
        }  
		catch(Exception e){
			TLog.log("Sound ThreadDownloadSamllFile : downloadonefile : Exception : " + e);
		}
		finally {
			try{
				if(null != is) {
					is.close();
				}	
			}catch(Exception e){
			}
			try{
				if(null != httpURLConnection) {
					httpURLConnection.disconnect();
				}	
			}catch(Exception e){
			}
			try{
				if(null != is) {
					is.close();
				}
			}catch(Exception e){
			}
			try{
				if(null != raf){
					raf.close();
				} 
			}catch(Exception e){
			}
			if(!bdone) {
				try{
					FileUtil.clearDirorFile(new File(ssavedpath));
				}catch(Exception e){
				}
			}
			return bdone;
		}
	}	
	
}
